package com.easymin.weixin.common.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.easymin.weixin.controller.v4.ResultTransport;
import com.easymin.weixin.controller.v5.utils.ErrorMapV5;
import com.easymin.weixin.controller.v5.utils.ResultV5;
import com.easymin.weixin.entity.sales.Coupon;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SalesApi {

    private static final Logger logger = LoggerFactory.getLogger(SalesApi.class);

    @Value("${module.sales.url}")
    private String salesApiGateway;

    @Autowired
    private RestTemplate restTemplate;
    /**
     * 查询单个优惠券.
     */
    public static final String COUPONS = "api/coupons/findOne/{id}?appKey={appKey}";
    /**
     * 修改优惠券状态.
     */
    public static final String UPDATE = "api/coupons/update/{id}?status={status}&appKey={appKey}";
    /**
     * 查询用户有效优惠券.
     */
    public static final String FIND_BY_PASSENGERID =
            "api/coupons/listValidByPassenger?passengerId={passengerId}"
                    + "&couponType={couponType}&appKey={appKey}";
    /**
     * 查询用户有效优惠券v4.
     */
    public static final String FIND_BY_PASSENGERID_V4 =
            "api/coupons/v4/listValidByPassenger?passengerId={passengerId}"
                    + "&couponType={couponType}&appKey={appKey}";
    /**
     * 查询单个优惠券v4.
     */
    public static final String COUPONS_V4 = "api/coupons/v4/findOne/{id}?appKey={appKey}";
    /**
     * 修改优惠券状态.
     */
    public static final String UPDATE_V4 = "api/coupons/v4/update/{id}?status={status}&appKey={appKey}";
    /**
     * 获取一张没有绑定的优惠券
     */
    public static final String FINE_ONE_COUPON = "api/coupons/findOneCoupon?appKey={appKey}&linesId={linesId}&phone={phone}" +
            "&passengerId={passengerId}&activityEvent={activityEvent}";



    /**
     * 获取一张没有绑定的优惠券
     * @param appKey
     * @param activityEvent
     * @param linesId
     * @return
     */
    public String findOneCoupon(String appKey, String linesId, String phone, Long passengerId, String activityEvent) {
        ResultV5 resultV5 = ErrorMapV5.ERR_SUCCESS.clone();
        String result = "";
        try {
            String buildApi = buildApi(FINE_ONE_COUPON);
            result = restTemplate.getForObject(buildApi, String.class, appKey,linesId, phone, passengerId, activityEvent);
            JSONObject json = JSON.parseObject(result);
            Integer code = json.getInteger("code");
            Coupon coupon = null;
            if (0 == code) {
                JSONObject data = json.getJSONObject("data");
                coupon = JSON.parseObject(data.toString(), Coupon.class);
            }
            resultV5.setData(coupon);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return result;
    }

    /**
     * 查询用户有效优惠券.
     *
     * @param passengerId 用户id
     * @param couponType  优惠券类型
     * @param appKey      系统key
     * @return List
     */
    public List<Coupon> findByPassengerId(Long passengerId, String couponType, String appKey) {
        List<Coupon> list = new ArrayList<Coupon>();
        try {
            String buildApi = buildApi(FIND_BY_PASSENGERID);

            String result = restTemplate.getForObject(buildApi, String.class, passengerId, couponType, appKey);
            JSONObject object = JSON.parseObject(result);
            int code = object.getIntValue("code");
            String message = object.getString("message");
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("code", code);
            map.put("message", message);
            if (code == 0) {
                JSONArray jsonArray = object.getJSONArray("data");
                list = JSON.parseArray(jsonArray.toString(), Coupon.class);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        return list;
    }

    /**
     * 查询用户有效优惠券v4.
     *
     * @param passengerId 用户id
     * @param couponType  优惠券类型
     * @param appKey      系统key
     * @return ResultTransport
     */
    public ResultTransport findByPassengerIdV4(Long passengerId, String couponType, String appKey) {
        String buildApi = buildApi(FIND_BY_PASSENGERID_V4);

        String result =
                restTemplate.getForObject(buildApi, String.class, passengerId, couponType, appKey);

        ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);

        return parseObject;
    }

    /**
     * 查询用户有效优惠券v4.
     *
     * @param passengerId 用户id
     * @param couponType  优惠券类型
     * @param appKey      系统key
     * @return JSONArray
     */
    public JSONArray findCouponV4(Long passengerId, String couponType, String appKey, String linesId) {
        StringBuilder sb = new StringBuilder(FIND_BY_PASSENGERID_V4);
        if(StringUtils.isNotBlank(linesId)){
            sb.append("&linesId={linesId}");
        }

        String buildApi = buildApi(sb.toString());

        String response = null;
        if(StringUtils.isNotBlank(linesId)){
            response = restTemplate.getForObject(buildApi, String.class, passengerId, couponType, appKey, linesId);
        } else {
            response = restTemplate.getForObject(buildApi, String.class, passengerId, couponType, appKey,null);
        }

        JSONObject jsonObject = JSON.parseObject(response);

        JSONArray jsonArray = jsonObject.getJSONArray("data");

        return jsonArray;
    }

    /**
     * 查询单个优惠券v4.
     *
     * @param id     优惠券id
     * @param appKey 系统key
     * @return map
     */
    public Map<String, Object> coupons(Long id, String appKey) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            String buildApi = buildApi(COUPONS);
            buildApi = buildApi.replaceAll("\\{id\\}", String.valueOf(id));
            String result = restTemplate.getForObject(buildApi, String.class, appKey);
            JSONObject object = JSON.parseObject(result);
            int code = object.getIntValue("code");
            String message = object.getString("message");
            map.put("code", code);
            map.put("message", message);
            if (code == 0) {
                JSONObject data = object.getJSONObject("data");
                Coupon coupon = JSON.parseObject(data.toString(), Coupon.class);
                map.put("data", coupon);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            map.put("code", -4);
            map.put("message", "内部服务器错误");
        }
        return map;
    }

    /**
     * 查询单个优惠券v4.
     *
     * @param id     优惠券id
     * @param appKey 系统key
     * @return ResultTransport
     */
    public ResultTransport couponsV4(Long id, String appKey) {

        String buildApi = buildApi(COUPONS_V4);

        buildApi = buildApi.replaceAll("\\{id\\}", String.valueOf(id));

        String result = restTemplate.getForObject(buildApi, String.class, appKey);

        ResultTransport parseObject = JSON.parseObject(result, ResultTransport.class);

        return parseObject;
    }

    /**
     * 修改优惠券状态.
     *
     * @param id     优惠券id
     * @param status 状态
     * @param appKey 系统key
     * @return map
     */
    public Map<String, Object> update(Long id, Integer status, String appKey) {
        Map<String, Object> map = new HashMap<String, Object>();
        String buildApi = buildApi(UPDATE);
        buildApi = buildApi.replaceAll("\\{id\\}", String.valueOf(id));

        try {
            restTemplate.put(buildApi, null, status, appKey);
            map.put("code", 0);
            map.put("message", "修改成功");
        } catch (Exception ex) {
            logger.error(ex.getMessage());
            map.put("code", -1);
            map.put("message", ex.getMessage());
        }
        return map;
    }

    /**
     * 修改优惠券状态V4.
     *
     * @param id     优惠券id
     * @param status 状态
     * @param appKey 系统key
     */

    public void updateV4(Long id, Integer status, String appKey) {
        String buildApi = buildApi(UPDATE_V4);
        buildApi = buildApi.replaceAll("\\{id\\}", String.valueOf(id));
        restTemplate.put(buildApi, null, status, appKey);
    }

    private String buildApi(String api) {
        StringBuilder builder = new StringBuilder();
        builder.append(salesApiGateway);
        if (!salesApiGateway.endsWith("/")) {
            builder.append("/");
        }
        builder.append(api);
        return builder.toString();
    }

}
